using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace Microsoft.WowAddonStudio.ProjectRefactor
{
	/// <summary>
	/// Merges source code changes into code file.
	/// </summary>
	public sealed class FrameXmlFileMerger : BaseFrameXmlMerger
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="FrameXmlFileMerger"/> class.
		/// </summary>
		/// <param name="fileName">Name of the file.</param>
		public FrameXmlFileMerger(string fileName)
			: base(fileName)
		{
		}

		#region IFrameXmlMerger Members

		/// <summary>
		/// Merges new text into file.
		/// </summary>
		/// <param name="newXml">The new XML.</param>
		public override void Merge(string newXml)
		{
			using (Stream stream = new FileStream(FileName, FileMode.Truncate, FileAccess.Write, FileShare.Read))
			{
				using (var writer = new StreamWriter(stream))
				{
					writer.Write(newXml);
				}
			}
		}

		/// <summary>
		/// Merges the new Lua code file name into the specified FramXml file as a refernce.
		/// </summary>
		/// <param name="frameXmlPath">Path of FrameXml file.</param>
		/// <param name="luaCodeFilePath">Path of Lua code file.</param>
		public override void MergeFrameName(string frameXmlPath, string luaCodeFilePath)
		{
			base.MergeFrameName(frameXmlPath, luaCodeFilePath);

			string luaFileName = Path.GetFileName(luaCodeFilePath);
			StringReader sourceReader;

			using (Stream stream = new FileStream(frameXmlPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
			{
				using (var streamReader = new StreamReader(stream))
				{
					sourceReader = new StringReader(streamReader.ReadToEnd());
				}
			}

			using (XmlReader reader = XmlReader.Create(sourceReader))
			{
				XElement root = XElement.Load(reader);
				ReplaceScriptFileAttribute(root, reader.NameTable, luaFileName);

				Merge(root.ToString());
			}
		}

		#endregion
	}
}